var yuming = 'http://activity.didadiandan.com';//服务器地址
var html = "";
var value = 0;
var imgUrl = "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1481508571&di=19d5d3251befcadd9fcfe33487ecf6f1&src=http://news.mydrivers.com/Img/20110518/04481549.png";
var optionValue = "all";
var drawInterval = "";
var personToPicture = "";//扫描二维码上墙定时器
var pubres = [];
var res = [];
var isDraw = false;//是否抽过奖
var initArr = [{name:'???',image:imgUrl}];

if(localStorage.te && localStorage.one && localStorage.two && localStorage.three && localStorage.xinyun) {
  $('.writePriceNum').hide();
  $('.container').show();
}else {
  $('.writePriceNum').show();
  $('.container').hide();
}
//
$('#enterDraw').click(function () {
  var xinyun = $('#xinyun').val();
  var three = $('#three').val();
  var two = $('#two').val();
  var one = $('#one').val();
  var te = $('#te').val();
  var totalInput = Number(xinyun)+Number(three)+Number(two)+Number(one)+Number(te);
  console.log(xinyun,three,two,one,te);
  console.log(value,totalInput);
  if(!xinyun || !three || !two || !one || !te) {
      alert("请填写完整的抽奖人数！");
      return false;
  }
  if(xinyun <= 0 || three <= 0 || two <= 0 || one <= 0 || te <= 0) {
    alert("抽奖人数必须为正整数！");
    return false;
  }
  // if(totalInput > value) {
  //   alert("您输入的中奖人数大于总的参与人数！");
  //   return false;
  // }

  localStorage.xinyun = xinyun;
  localStorage.three = three;
  localStorage.two = two;
  localStorage.one = one;
  localStorage.te = te;
  $('.writePriceNum').hide();
  $('.container').show();
  renderUserLists();//重置一次
});
//
// 初始话渲染
renderUserLists();
personToPicture = setInterval(function () {
  console.log(1);
    renderUserLists();
},10*1000);

$('#select').on('change',function () {
  html = "";
  // console.log(this.options[this.options.selectedIndex].value);
  optionValue = this.options[this.options.selectedIndex].value;
  if(optionValue == "all") {
    personToPicture = setInterval(function () {
      console.log(1);
        renderUserLists();
    },10*1000);
  }else {
    clearInterval(personToPicture);
  }
  switch (optionValue) {
    case '四等奖':
      value = Number(localStorage.xinyun);
      $('.productImg img').attr({'src':'./img/showOne.png'});
      $('.productDesc p').html('四等奖：HE衬衫');
      break;
    case '三等奖':
      value = Number(localStorage.three);
      $('.productImg img').attr({'src':'./img/showOne.png'});
      $('.productDesc p').html('三等奖：奔驰拉杆箱');
      break;
    case '二等奖':
      value = Number(localStorage.two);
      $('.productImg img').attr({'src':'./img/showOne.png'});
      $('.productDesc p').html('二等奖：爱直棒摄影套餐');
      break;
    case '一等奖':
      value = Number(localStorage.one);
      $('.productImg img').attr({'src':'./img/showOne.png'});
      $('.productDesc p').html('一等奖：奔驰折叠自行车');
      break;
    case '特等奖':
      value = Number(localStorage.te);
      $('.productImg img').attr({'src':'./img/showOne.png'});
      $('.productDesc p').html('特等奖：奥克斯空调');
      break;
    default:
      value = userLists.length;
      $('.productImg img').attr({'src':'./img/showOne.png'});
      $('.productDesc p').html('四等奖：HE衬衫');
      renderHtml(value,html,'userLists');
      return false;
  };
  checkHowToRender();
});

$('#startStop').click(function () {
  if(optionValue == "all") {
    alert("您选择抽奖等级！");
    return false;
  }
  if(isDraw) {
    alert("您已经抽过该奖项！");
    return false;
  }
  var content = $(this).html();
  if(content == "开始") {
    $('#select').attr({"disabled":"disabled"});
    drawPrice();
    $(this).html("停止");
  }else {
    $('#select').removeAttr("disabled");
    $.post(yuming+'/web/draw/start',{levelName:optionValue,num:value},function (data) {
        clearInterval(drawInterval);
        if(data.code == 100) {
            isDraw = true;
            res = data.object;
            // console.log(res);
            html = "";
            renderHtml(value,html,'res');
        }else {
          alert("抽奖无效："+data.message);
        }
    },"json");
    $(this).html("开始");
  }
})

$('#clear').click(function () {
  if(optionValue == "all") {
    alert("这是参与人，您不能清空！");
    return false;
  }
  var r = confirm("您确定要清空"+optionValue+"嘛？");
  if (r==true) {
    $.post(yuming+'/web/draw/clear',{levelName:optionValue},function (data) {
        if(data.code == 100) {
            isDraw = false;
            renderHtml(value,html,'pubres');
            alert("清除"+optionValue+"成功！");
        }else {
          alert(data.message);
        }
    },"json");
  }
})
$('#reset').click(function () {
  $.post(yuming+'/web/draw/clear',{},function (data) {
      if(data.code == 100) {
        var n = confirm("您确定要重置所有抽奖并重新输入抽奖人数嘛？")
        if(n) {
          localStorage.clear();
          window.location.reload();
        }
      }else {
        alert(data.message);
      }
  },"json");
})

function renderUserLists() {
  $.post(yuming+'/web/draw/list',{},function (data) {
      if(data.code == 100) {
          userLists = data.object;
          value = userLists.length;
          $('#allPerson').html('（共'+userLists.length+'人参与）')
          $('#select option').each(function (i,n) {
            // console.log(i,n);
            var content = ['参与人'+userLists.length+'人','四等奖'+localStorage.xinyun+'人','三等奖'+localStorage.three+'人','二等奖'+localStorage.two+'人','一等奖'+localStorage.one+'人','特等奖'+localStorage.te+'人']
            $(n).html(content[i])
          });
          renderHtml(value,html,'userLists');
          // checkHowToRender();
      }else {
        alert(data.message);
      }
  },"json");
}

function renderHtml(value,html,type) {
  html = "";
  if(type == 'userLists') {//渲染全部用户信息
    for (var i = 0; i < userLists.length; i++) {
      html +=
      '<div>'+
        '<img src='+(userLists[i].image || imgUrl)+' alt="">'+
        '<span>'+userLists[i].name+'</span>'+
      '</div>'
    }
  }else if(type == 'pubres') {
    for (var i = 0; i < value; i++) {
      html +=
      '<div>'+
        '<img src='+initArr[0].image+' alt="">'+
        '<span>'+initArr[0].name+'</span>'+
      '</div>'
    }
  }else {
    for (var i = 0; i < value; i++) {
      // if(!res[i].hasOwnProperty('image')) {
      //   res[i].image = imgUrl;
      // }
      html +=
      '<div>'+
        '<img src='+(res[i].image || imgUrl)+' alt="">'+
        '<span>'+res[i].name+'</span>'+
      '</div>'
    }
  }
  $('.leftul li ').html(html);
}

function drawPrice() {
  var randomMax = userLists.length;
  drawInterval = setInterval(function () {
    html = "";
    for (var i = 0; i < value; i++) {
      var randomPerson = userLists[Math.floor(Math.random()*randomMax)];
      html +=
      '<div>'+
        '<img src='+(randomPerson.image || imgUrl)+' alt="">'+
        '<span>'+randomPerson.name+'</span>'+
      '</div>'
    }
    $('.leftul li').html(html);
  },100)
}

function checkHowToRender() {
  $.post(yuming+'/web/draw/view',{levelName:optionValue},function (data) {
      if(data.code == 100) {
          res = data.object;
          if(res.length == 0) {
            isDraw = false;
            renderHtml(value,html,'pubres');
          }else {
            for (var i = 0; i < res.length; i++) {
              res[i].name = res[i].weixinName
            }
            // console.log(res);
            isDraw = true;
            html = "";
            renderHtml(res.length,html,'res');
          }
      }else {
        alert(data.message);
      }
  },"json");
}
